package dao

import (
	"go-weixin/app/usercenter/model"
	"go-weixin/common/chendb"
	// "go-weixin/common/utils"
)

type PowerDao struct {
	engine chendb.ChenDb
}

func NewPowerDao(engine chendb.ChenDb) *PowerDao {
	return &PowerDao{
		engine: engine,
	}
}
func (u PowerDao) PowerExistByName(name string) (bool, error) {
	return u.engine.Exist(&model.PowerModel{
		Name: name,
	})
}

func (u PowerDao) PowerUpdateExisByName(name string, id int64) (bool, error) {
	return u.engine.Where("name = ? AND id != ?", name, id).Exist(&model.PowerModel{})
}
func (u PowerDao) PowerAdd(power *model.PowerModel) (int64, error) {
	return u.engine.Insert(power)
}

func (u PowerDao) PowerExistById(id int64) (bool, error) {
	return u.engine.ID(id).Exist(&model.PowerModel{})
}
func (u PowerDao) PowerUpdate(id int64, power *model.PowerModel) (int64, error) {
	return u.engine.ID(id).Update(power)
}
func (u PowerDao) PowerList(limit int64, offset int64, powerList *[]model.PowerModel) error {
	return u.engine.Limit(int(limit), int(offset)).Find(powerList)
}
func (u PowerDao) GetPowerById(id int64, power *model.PowerModel) (bool, error) {
	return u.engine.ID(id).Get(power)
}

func (u PowerDao) PowerGetRoleById(id int64, roleList *[]model.RoleModel) error {
	rp := new(model.RolePowerModel)
	r := new(model.RoleModel)
	return u.engine.Table(rp.TableName()).Alias("rp").
		Join("INNER", []string{r.TableName(), "r"}, "rp.role_id = r.id").
		Where("rp.power_id = ?", id).
		Select("r.*").
		Find(roleList)
}

func (u PowerDao) PowerGetUserById(id int64, userList *[]model.UserModel) error {
	rp := new(model.RolePowerModel)
	r := new(model.RoleModel)
	ur := new(model.UserRoleModel)
	us := new(model.UserModel)
	return u.engine.Table(rp.TableName()).Alias("rp").Join("INNER", []string{r.TableName(), "r"}, "rp.role_id = r.id").
		Join("INNER", []string{ur.TableName(), "ur"}, "ur.role_id = r.id").
		Join("INNER", []string{us.TableName(), "u"}, "u.id = ur.user_id").
		Where("rp.power_id = ?", id).
		Select("u.*").
		Unscoped().
		Find(userList)
}
